<template>
  <view class="statistics-container">
    <!-- 销售概览 -->
    <view class="overview-section">
      <view class="overview-item">
        <text class="overview-value">¥{{overview.totalSales}}</text>
        <text class="overview-label">总销售额</text>
      </view>
      <view class="overview-item">
        <text class="overview-value">{{overview.totalOrders}}</text>
        <text class="overview-label">总订单数</text>
      </view>
      <view class="overview-item">
        <text class="overview-value">¥{{overview.averageOrder}}</text>
        <text class="overview-label">平均客单价</text>
      </view>
    </view>

    <!-- 销售趋势图 -->
    <view class="chart-section">
      <view class="section-header">
        <text class="section-title">销售趋势</text>
      </view>
      <view class="native-bar-chart">
        <view class="bar-group" v-for="(item, index) in chartData" :key="index">
          <view class="bar-container">
            <view class="bar bar-sales" :style="{height: item.salesHeight + '%'}" @click="showBarValue(index, 'sales')">
              <text v-if="item.showSalesValue" class="bar-value">¥{{item.sales}}</text>
            </view>
            <view class="bar bar-orders" :style="{height: item.ordersHeight + '%'}" @click="showBarValue(index, 'orders')">
              <text v-if="item.showOrdersValue" class="bar-value">{{item.orders}}</text>
            </view>
          </view>
          <view class="bar-label">{{item.date}}</view>
        </view>
      </view>
    </view>

    <!-- 热销商品 -->
    <view class="hot-products-section">
      <view class="section-header">
        <text class="section-title">热销商品</text>
      </view>
      <view class="product-list">
        <view class="product-item" v-for="(product, index) in hotProducts" :key="index">
          <view class="product-rank">{{index + 1}}</view>
          <view class="product-info">
            <text class="product-name">{{product.name}}</text>
            <text class="product-sales">销量：{{product.sales}}份</text>
          </view>
          <text class="product-amount">¥{{product.amount}}</text>
        </view>
      </view>
    </view>

    <!-- 时段分析 -->
    <view class="time-analysis-section">
      <view class="section-header">
        <text class="section-title">时段分析</text>
      </view>
      <view class="time-list">
        <view class="time-item" v-for="(time, index) in timeAnalysis" :key="index">
          <text class="time-period">{{time.period}}</text>
          <view class="time-bar">
            <view class="bar-fill" :style="{width: time.percentage + '%'}"></view>
          </view>
          <text class="time-percentage">{{time.percentage}}%</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { orderApi } from '../../utils/api.js'

export default {
  data() {
    return {
      selectedMonth: this.getCurrentMonth(),
      loading: false,
      overview: {
        totalSales: 0,
        totalOrders: 0,
        averageOrder: 0
      },
      hotProducts: [],
      timeAnalysis: [],
      chartData: []
    }
  },
  onLoad() {
    this.loadStatistics()
  },
  onShow() {
    this.loadStatistics()
  },
  methods: {
    getCurrentMonth() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      return `${year}-${month}`
    },
    async loadStatistics() {
      try {
        this.loading = true
        const response = await orderApi.getOrdersByDate()
        if (response.code === 200) {
          this.processStatisticsData(response.data)
        } else {
          uni.showToast({ title: response.message || '获取统计数据失败', icon: 'none' })
        }
      } catch (error) {
        uni.showToast({ title: '获取统计数据失败', icon: 'none' })
      } finally {
        this.loading = false
      }
    },
    processStatisticsData(orderItemDTOs) {
      if (!orderItemDTOs || orderItemDTOs.length === 0) {
        this.updateOverview(0, 0, 0)
        this.hotProducts = []
        this.timeAnalysis = []
        this.chartData = []
        return
      }
      const orderMap = new Map()
      const dishMap = new Map()
      const periodMap = new Map([
        ['11:00-13:00', 0],
        ['17:00-19:00', 0],
        ['19:00-21:00', 0],
        ['其他时段', 0]
      ])
      orderItemDTOs.forEach(dto => {
        const orderId = dto.customerOrder.orderId
        if (!orderMap.has(orderId)) {
          orderMap.set(orderId, {
            id: orderId,
            totalPrice: dto.customerOrder.payableAmount || 0,
            status: dto.customerOrder.orderStatus,
            createTime: dto.customerOrder.placeOrderTime
          })
        }
        // 统计菜品
        if (dto.customerOrderItem && dto.dishes && dto.dishes.length > 0) {
          const dish = dto.dishes[0]
          const dishId = dish.dishId
          if (!dishMap.has(dishId)) {
            dishMap.set(dishId, {
              name: dish.dishName || `菜品${dishId}`,
              sales: 0,
              amount: 0
            })
          }
          const dishData = dishMap.get(dishId)
          dishData.sales += dto.customerOrderItem.quantity || 1
          dishData.amount += (dish.price || 0) * (dto.customerOrderItem.quantity || 1)
        }
        // 统计时段
        if (dto.customerOrder && dto.customerOrder.placeOrderTime) {
          const date = new Date(dto.customerOrder.placeOrderTime)
          const hour = date.getHours()
          let period = '其他时段'
          if (hour >= 11 && hour < 13) period = '11:00-13:00'
          else if (hour >= 17 && hour < 19) period = '17:00-19:00'
          else if (hour >= 19 && hour < 21) period = '19:00-21:00'
          periodMap.set(period, (periodMap.get(period) || 0) + 1)
        }
      })
      const orders = Array.from(orderMap.values())
      const paidOrders = orders.filter(order => order.status === 'PAID')
      const totalSales = paidOrders.reduce((sum, order) => sum + order.totalPrice, 0)
      const totalOrders = orders.length
      const averageOrder = totalOrders > 0 ? (totalSales / totalOrders).toFixed(2) : 0
      this.updateOverview(totalSales, totalOrders, averageOrder)
      // 热销商品排序
      this.hotProducts = Array.from(dishMap.values()).sort((a, b) => b.sales - a.sales).slice(0, 5)
      // 时段分析排序和占比
      const periodArr = Array.from(periodMap.entries()).map(([period, count]) => ({ period, count }))
      const totalPeriodOrders = periodArr.reduce((sum, item) => sum + item.count, 0) || 1
      this.timeAnalysis = periodArr
        .map(item => ({
          period: item.period,
          percentage: Math.round((item.count / totalPeriodOrders) * 100)
        }))
        .sort((a, b) => b.percentage - a.percentage)
      // 柱状图数据
      this.updateChartData(orders)
    },
    updateOverview(totalSales, totalOrders, averageOrder) {
      this.overview = {
        totalSales: totalSales.toFixed(2),
        totalOrders: totalOrders,
        averageOrder: averageOrder
      }
    },
    updateChartData(orders) {
      if (!orders || orders.length === 0) {
        this.chartData = []
        return
      }
      // 按日期分组
      const dateMap = new Map()
      orders.forEach(order => {
        const dateObj = new Date(order.createTime || order.placeOrderTime)
        const year = dateObj.getFullYear()
        const month = String(dateObj.getMonth() + 1).padStart(2, '0')
        const day = String(dateObj.getDate()).padStart(2, '0')
        const date = `${month}-${day}`
        if (!dateMap.has(date)) {
          dateMap.set(date, { date, sales: 0, orders: 0 })
        }
        const dateData = dateMap.get(date)
        dateData.orders += 1
        if (order.status === 'PAID') {
          dateData.sales += order.totalPrice
        }
      })
      // 排序&取最近7天
      const chartDataArray = Array.from(dateMap.values()).sort((a, b) => a.date.localeCompare(b.date)).slice(-7)
      const maxSales = Math.max(...chartDataArray.map(item => item.sales), 1)
      const maxOrders = Math.max(...chartDataArray.map(item => item.orders), 1)
      this.chartData = chartDataArray.map(item => ({
        ...item,
        salesHeight: (item.sales / maxSales) * 100,
        ordersHeight: (item.orders / maxOrders) * 100,
        showSalesValue: false,
        showOrdersValue: false
      }))
    },
    showBarValue(index, type) {
      this.chartData = this.chartData.map((item, i) => {
        if (i === index) {
          return {
            ...item,
            showSalesValue: type === 'sales',
            showOrdersValue: type === 'orders'
          }
        } else {
          return {
            ...item,
            showSalesValue: false,
            showOrdersValue: false
          }
        }
      })
    }
  }
}
</script>

<style>
.statistics-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.filter-section {
  background-color: #ffffff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.month-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

.picker-arrow {
  font-size: 24rpx;
  color: #999;
}

.overview-section {
  display: flex;
  justify-content: space-around;
  background-color: #ffffff;
  padding: 30rpx 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.overview-item {
  text-align: center;
}

.overview-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.overview-label {
  font-size: 24rpx;
  color: #999;
}

.chart-section {
  background-color: #ffffff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.native-bar-chart {
  display: flex;
  align-items: flex-end;
  height: 260rpx;
  padding: 20rpx 0 0 0;
  justify-content: space-around;
  background: #f9f9f9;
  border-radius: 8rpx;
}
.bar-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 70rpx;
}
.bar-container {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
  gap: 20rpx;
  height: 200rpx;
}
.bar {
  width: 18rpx;
  border-radius: 8rpx 8rpx 0 0;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  position: relative;
  transition: height 0.3s;
  min-height: 6rpx;
  cursor: pointer;
}
.bar-sales {
  background: linear-gradient(to top, #C70209, #ff6b6b);
}
.bar-orders {
  background: linear-gradient(to top, #1890ff, #69c0ff);
}
.bar-value {
  position: absolute;
  top: -28rpx;
  left: 50%;
  transform: translateX(-50%);
  font-size: 18rpx;
  color: #333;
  background: #fff;
  padding: 2rpx 6rpx;
  border-radius: 4rpx;
  white-space: nowrap;
  font-weight: bold;
  border: 1rpx solid #e8e8e8;
  box-shadow: 0 2rpx 4rpx rgba(0,0,0,0.08);
  z-index: 2;
}
.bar-label {
  margin-top: 8rpx;
  font-size: 18rpx;
  color: #666;
}

.hot-products-section {
  background-color: #ffffff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
}

.product-rank {
  width: 40rpx;
  height: 40rpx;
  background-color: #C70209;
  color: #ffffff;
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  margin-right: 20rpx;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 6rpx;
  display: block;
}

.product-sales {
  font-size: 24rpx;
  color: #999;
}

.product-amount {
  font-size: 32rpx;
  color: #C70209;
  font-weight: bold;
}

.time-analysis-section {
  background-color: #ffffff;
  padding: 20rpx;
  border-radius: 12rpx;
}

.time-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.time-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.time-period {
  width: 160rpx;
  font-size: 26rpx;
  color: #333;
}

.time-bar {
  flex: 1;
  height: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  background-color: #C70209;
  border-radius: 10rpx;
  transition: width 0.3s ease;
}

.time-percentage {
  width: 80rpx;
  font-size: 26rpx;
  color: #666;
  text-align: right;
}
</style> 